﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WindowsLive.Writer.Api;
using ScottIsAFool;

namespace WordpressFeaturedImagePlugin
{
    public partial class frmOptions : Form
    {
        Dictionary<string, PluginSettings> AllSettings;
        PluginSettings selectedSettings;
        IProperties m_properties;
        Blog[] blogs;
        bool isloading;

        public frmOptions(IProperties properties)
        {
            InitializeComponent();
            AllSettings = new Dictionary<string, PluginSettings>();
            m_properties = properties;
            Load += new EventHandler(frmOptions_Load);            
        }

        void frmOptions_Load(object sender, EventArgs e)
        {
            foreach (var property in m_properties.SubPropertyNames)
                AllSettings.Add(property, new PluginSettings(m_properties.GetSubProperties(property)));

            blogs = (from b in WriterUtils.ConfiguredBlogs()
                    where b.ServiceName.ToLower().Contains("wordpress") &&
                          !b.ServiceName.ToLower().Contains(".com")
                    select b).ToArray();
            cbBlogs.DataSource = blogs;
            cbBlogs.DisplayMember = "Name";
            lnkDelete.Visible = !string.IsNullOrEmpty(selectedSettings.Password);
            chbxUsePostIdAsImageName.Checked = selectedSettings.UsePostIdAsImageName;
        }       

        private void cbBlogs_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (btnApply.Enabled)
            {
                DialogResult result = MessageBox.Show("You have changes to save, do you wish to save them now?", "Save changes?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    btnApply_Click(this, null);
                }
            }
            if (cbBlogs.SelectedItem != null)
            {
                Blog blog = cbBlogs.SelectedItem as Blog;
                chlbCategories.DataSource = blog.Categories;                
                if (AllSettings.Count > 0)
                {
                    try
                    {
                        selectedSettings = (AllSettings.Single(x => x.Key == blog.ID)).Value;
                    }
                    catch
                    {
                        lnkDelete.Visible = false;
                        return;
                    }
                    if (selectedSettings != null)
                    {
                        isloading = true;
                        foreach (var cat in WriterUtils.ParseString(selectedSettings.CheckedCategories))
                        {
                            chlbCategories.SetItemChecked(chlbCategories.Items.IndexOf(cat), true);
                        }
                        isloading = false;
                        lnkDelete.Visible = !string.IsNullOrEmpty(selectedSettings.Password);
                        chbxUsePostIdAsImageName.Checked = selectedSettings.UsePostIdAsImageName;
                    }
                }
            }
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            Blog blog = cbBlogs.SelectedItem as Blog;
            if (selectedSettings == null)
            {
                selectedSettings = new PluginSettings(m_properties.GetSubProperties(blog.ID));
                AllSettings.Add(blog.ID, selectedSettings);
            }

            if (chlbCategories.CheckedItems.Count > 0)
            {
                string chosenCategories = string.Empty;
                foreach (string item in chlbCategories.CheckedItems)
                {
                    chosenCategories += item + ",";
                }
                chosenCategories = chosenCategories.Substring(0, chosenCategories.Length - 1);
                selectedSettings.CheckedCategories = chosenCategories;
            }
            else
            {
                selectedSettings.CheckedCategories = string.Empty;
            }
            selectedSettings.UsePostIdAsImageName = chbxUsePostIdAsImageName.Checked;
            btnApply.Enabled = false;
        }

        private void chlbCategories_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (!isloading)
                if (!btnApply.Enabled)
                    btnApply.Enabled = true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (btnApply.Enabled)
            {
                DialogResult result = MessageBox.Show("You have changes to save, do you wish to save them now?", "Save changes?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    btnApply_Click(this, null);
                }
                else if (result == DialogResult.Cancel)
                {
                    return;
                }                
            }
            Close();
        }

        private void lnkDelete_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (MessageBox.Show("Are you sure you wish to clear the saved password?\nThis action cannot be undone.",
                               "Are you sure?",
                               MessageBoxButtons.YesNo,
                               MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                selectedSettings.Password = string.Empty;
                lnkDelete.Visible = false;
            }
        }

        private void chbxUsePostIdAsImageName_Click(object sender, EventArgs e)
        {
            if (!btnApply.Enabled)
                btnApply.Enabled = true;
        }

        private void lnkWordpressNet_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://visualizationtools.net/default/the-lab/wordpress-xml-rpc-wrapper-for-net/");
        }

    }
}
